import 'dart:async';

import 'package:flutter/material.dart';
import 'package:part_refresh_demo/Model/time_model.dart';
import 'package:part_refresh_demo/widgets/my_inheritedwidget.dart';
import 'package:part_refresh_demo/widgets/my_reapintboundary.dart';
import 'package:part_refresh_demo/widgets/part_refresh_widget.dart';
import 'package:provider/provider.dart';
import 'package:zl_widgets_kit/src/zlbutton.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  void dispose() {
    // 关闭流
    _streamController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            partRefreshProvider(),
            partRefreshCustom(),
            partRefreshStatefulBuilder(),
            partRefreshFutureBuilder(),
            partRefreshStreamBuilder(),
            partRefreshNotifier(),
            partRefreshInheritedWidget(),
            MyReapintBoundary(), // 据说可以节省性能
            Text('对照 widget : $_counter', style: Theme.of(context).textTheme.headline4 ),
            globalRefreshButton(),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          _counter++;
          // 1、 局部刷新
          globalKey.currentState!.update();

          // 2、StateSetter
          _stateSetter(() { });
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }

  //1、创建一个globalKey
  GlobalKey<PartRefreshWidgetState> globalKey = GlobalKey(debugLabel: "Jiaozl-globalKey");


  Widget partRefreshCustom() {
    return Column(
      children: [
        PartRefreshWidget(globalKey, (){
          return Text("GlobalKey : " + _counter.toString(), style: Theme.of(context).textTheme.headline4,);
        }),
        PartRefreshWidget(GlobalKey(), (){
          return Text(_counter.toString(), style: Theme.of(context).textTheme.headline4,);
        }),
      ],
    );
  }

  // 2、stateSetter & StatefulBuilder
  late StateSetter _stateSetter;

  StatefulBuilder partRefreshStatefulBuilder() {
    return StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) {
      _stateSetter = stateSetter;
      return Text("StatefulBuilder : " + _counter.toString(), style: Theme.of(context).textTheme.headline4,);
    });
  }

  // 3. FutureBuilder
  Future<String> mockNetworkData() async {
    return Future.delayed(Duration(seconds: 2), ()=>"mock 数据");
  }

  FutureBuilder partRefreshFutureBuilder() {
    return FutureBuilder(
      future: mockNetworkData(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return Text("Error: ${snapshot.error}");
            } else {
              // 请求成功，显示数据
              return Text("Contents: ${snapshot.data}");
            }
          } else {
            return CircularProgressIndicator();
          }
      },
    );
  }

  // 4、StreamBuilder
  final StreamController _streamController = StreamController<int>();

  Stream ss = Stream.periodic(Duration(seconds: 1), (value) {
    return DateTime.now().toString() + " --- ${value}";
  });

  StreamBuilder partRefreshStreamBuilder() {
    return StreamBuilder(
      stream: ss,
      initialData: 0,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        return ZLButton("StreamBuilder : " + _counter.toString() + "\n" + snapshot.data, callback: () async {
            _counter++;
            _streamController.sink.add(_counter);
        });
      },
    );
  }

  // 5. InheritedWidget
  Widget partRefreshInheritedWidget() {
    return Container(
        color: Colors.tealAccent,
        child: MyInheritedWidget(
          child: Column(
            children: [
              WidgetA(),
              WidgetB(),
              WidgetC(),
            ],
          ),
        )
    );
  }

  // 6. ValueNotifier 和 ValueListenableBuilder
  var a_value_noti = ValueNotifier<int>(10);

  Widget partRefreshNotifier() {
    return Container(
      color: Colors.lightGreenAccent,
      child: Column(
        children: [
          ValueListenableBuilder(
              valueListenable: a_value_noti,
              builder: (BuildContext context, int value, Widget? child) {
                return Text('ValueNotifier : ' + value.toString());
              }
          ),
          GestureDetector(
            onTap: () {
              a_value_noti.value = a_value_noti.value + 1;
            },
            child: Text('点击修改A的文案'),
          ),
        ],
      ),
    );
  }

  // 7、Provider & ChangeNotifierProvider
  ChangeNotifierProvider partRefreshProvider() {
    return ChangeNotifierProvider<TimerModel>(
        create: (context) => TimerModel(),
        child: Consumer<TimerModel>(builder: (context, timerModel, _) {
          return ZLButton(
              timerModel.count == 0 ? "Provider 获取验证码" : 'Provider ${timerModel.count} 秒后重发',
              textStyle: timerModel.count == 0 ? TextStyle(color: Colors.blue, fontSize: 14) : TextStyle(color: Colors.grey, fontSize: 14),
              bgColor: Colors.transparent,
              callback: () async {
                if (timerModel.count == 0) {
                  timerModel.startTimer();
                }
              });
          }
        )
    );
  }

  Widget globalRefreshButton() {
    return ElevatedButton(
      onPressed: () async {
        setState(() { });
      },
      child: Text("全局更新", style: Theme.of(context).textTheme.headline4,),
      style: ButtonStyle(
        elevation: MaterialStateProperty.all(0),
        enableFeedback: false,
        splashFactory: NoSplash.splashFactory,
        //将按钮背景设置为透明
        backgroundColor: MaterialStateProperty.all(Colors.redAccent),
      ),
    );
  }

}
